<template>
  <div class="vocabulary-page-container">
    <div class="left-div">
      <left-bar :tabs="leftBarTabs" @tab-click="handleTabClick"/>
    </div>
    <div class="right-body" @scroll="handleScroll">
      <div class="btn-head">
        <el-row :gutter="20">
          <el-col :span="3">
            <el-select
              v-model="selectedBookTypeValue"
              placeholder="请选择教材版本"
              clearable
              @change="handleBookTypeChange"
            >
              <el-option
                v-for="item in typeOptions"
                :key="item.id"
                :label="item.label"
                :value="item.id"
              />
            </el-select>
          </el-col>
          <el-col :span="3">
            <el-input
              v-model="keyword"
              placeholder="教材名称"
              clearable
              @clear="handleSearch"
              @keydown.enter.native="handleSearch"
            />
          </el-col>
          <el-col :span="6">
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button v-if="attribution !== 'sys'" type="primary" @click="upWord">新建词库</el-button>
          </el-col>
        </el-row>
      </div>
      <div v-if="books.length > 0 && books[0].children.length > 0" class="book-list">
        <div v-for="(item,index) in books" :key="index">
          <div>
            <span class="type-label">{{ item.parentLabel }}</span>
            <span v-if="attribution === 'stu'" class="type-label">的定制词库</span>
          </div>
          <div class="book-div">
            <div v-for="(children,cIndex) in item.children" :key="cIndex" class="card">
              <div class="content">
                <div class="imgBx"><img src="@/assets/bookCover.png" alt=""/></div>
                <div class="contentBx">
                  <h3>{{ children.label }}<br><span>{{ children.wordNum }} 单词</span><br><span>{{
                      children.studyTotal
                    }} 人学过</span></h3>
                </div>
                <ul class="sci">
                  <li @click="openDialog(children,'wordTable')">
                    <span>词表</span>
                  </li>
                  <li @click="openDialog(children,'openBook')">
                    <span>开通</span>
                  </li>
                  <li>
                    <span>进度</span>
                  </li>
                  <li v-if="attribution !== 'sys'" @click="delBook(children)">
                    <span>删除</span>
                  </li>
                </ul>
              </div>
            </div>
          </div>
        </div>
        <div v-if="loading" class="loading">加载中...</div>
        <div v-if="finished" class="loading">没有更多了</div>
      </div>
      <el-empty v-else description="这里空空的"></el-empty>
    </div>
    <!-- 子组件对话框 -->
    <word-dialog v-model="wordTableVisible" :lib-id="currentLibId"/>
    <up-word-dialog
      v-if="upWordVisible"
      v-model="upWordVisible"
      :attribution="attribution"
      :stu-id="selectStudent.id"
      @uploaded="handleSearch"
    />
    <student-choose-dialog v-if="studentChooseVisible" v-model="studentChooseVisible" @on-select="chooseStudent"/>
    <student-choose-dialog v-if="studentChooseOpenBookVisible" v-model="studentChooseOpenBookVisible"
                           @on-select="openBookForChooseStudent"
    />
  </div>
</template>

<script>

import LeftBar from '@/views/component/leftBar.vue'
import { delBook, queryPage, sysRootTypeList } from '@/api/wordSystemLibraryType'
import WordDialog from '@/views/vocabulary/component/wordPage.vue'
import UpWordDialog from '@/views/vocabulary/component/upWordDialog.vue'
import StudentChooseDialog from '@/views/student/components/studentChooseDialog.vue'
import { lexiconActivationJustSave } from '@/api/wordSystemLibraryTypeStu'

export default {
  name: 'Vocabulary',
  components: { StudentChooseDialog, UpWordDialog, WordDialog, LeftBar },
  data() {
    return {
      leftBarTabs: [
        { icon: 'fa-solid fa-server', alt: '官方词库', color: '#ae5ef2' },
        { icon: 'fa-solid fa-heart', alt: '我的词库', color: '#2f8fcf' },
        { icon: 'fa-solid fa-users', alt: '学生词库', color: '#2fcf51' }
      ],
      books: [], // 当前显示的数据
      page: 1, // 当前页
      pageSize: 20, // 每次加载数量
      loading: false,
      finished: false,
      keyword: '',
      attribution: 'sys',
      wordTableVisible: false,
      upWordVisible: false,
      studentChooseVisible: false,
      studentChooseOpenBookVisible: false,
      currentLibId: null,
      selectStudent: {},
      selectBook: {},
      typeOptions: [],
      selectedBookTypeValue: ''
    }
  },
  mounted() {
    this.loadData() // 初始化加载
    this.loadSysRootTypeList()
  },
  methods: {
    handleBookTypeChange() {
      this.handleSearch()
    },
    handleTabClick({ index, tab }) {
      if (index === 0) {
        this.attribution = 'sys'
      } else if (index === 1) {
        this.attribution = 'me'
      } else if (index === 2) {
        this.attribution = 'stu'
      }
      this.handleSearch()
    },
    handleSearch() {
      this.page = 1
      this.books = []
      this.finished = false
      this.loadData()
    },
    upWord() {
      if (this.attribution === 'me') {
        this.upWordVisible = true
      } else {
        this.studentChooseVisible = true
      }
    },
    async loadSysRootTypeList() {
      const res = await sysRootTypeList()
      this.typeOptions = res
    },
    async loadData() {
      if (this.loading || this.finished) return
      this.loading = true

      const res = await queryPage({
        page: {
          pageNum: this.page,
          pageSize: this.pageSize
        },
        param: {
          attribution: this.attribution,
          keyword: this.keyword,
          parentId: this.selectedBookTypeValue
        }
      })

      if (res?.records?.length > 0) {
        const addArr = []
        for (const item of res.records) {
          let flag = false
          for (const book of this.books) {
            if (book.parentLabel === item.parentLabel) {
              book.children.push(...item.children)
              flag = true
              break
            }
          }
          if (!flag) {
            addArr.push(item)
          }
        }
        this.books.push(...addArr)
        this.page++
      } else {
        this.finished = true
      }
      this.loading = false
    },

    // 滚动监听
    handleScroll(e) {
      const el = e.target

      if (el.scrollTop + el.clientHeight >= el.scrollHeight - 50) {
        this.loadData()
      }
    },
    openDialog(row, type) {
      this.currentLibId = row.id
      if (type === 'wordTable') {
        this.wordTableVisible = true
      } else if (type === 'openBook') {
        this.studentChooseOpenBookVisible = true
        this.selectBook = row
      }
    },
    async openBookForChooseStudent(student) {
      this.studentChooseOpenBookVisible = false
      await lexiconActivationJustSave({
        libTypeId: this.selectBook.id,
        stuId: student.id
      })
      this.$notify({ type: 'success', message: '开通成功' })
    },
    chooseStudent(student) {
      this.studentChooseVisible = false
      this.selectStudent = student
      this.upWordVisible = true
    },
    delBook(book) {
      this.$confirm('确定要删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delBook({ id: book.id }).then(() => {
          this.$notify.success({ message: '删除成功' })
          this.handleSearch()
        })
      }).catch(() => {
        this.$notify.info({ message: '已取消删除' })
      })
    }
  }
}
</script>
<style scoped>
.vocabulary-page-container {
  display: flex;
  align-items: center; /* 垂直方向居中 */
  justify-content: space-between; /* 水平方向居中 */
  height: calc(100vh - 85px);
  /*padding: 20px;*/
  width: 100%;
  box-sizing: border-box;

  .left-div {
    display: flex;
    align-items: center; /* 垂直方向居中 */
    justify-content: center; /* 水平方向居中 */
    width: 100px;
  }

  .right-body {
    background-color: white;
    width: calc(100% - 110px);
    justify-content: space-between;
    height: 100%;
    border-radius: 16px; /* 圆角 */
    box-shadow: 0 8px 24px rgba(8, 8, 8, 0.15); /* 阴影 */
    overflow-y: auto; /* ✅ 如果内容超出高度，内部滚动 */
  }
}

.book-div {
  display: flex;
  flex-wrap: wrap; /* ✅ 允许子元素换行 */
  align-content: flex-start; /* ✅ 控制多行对齐方式 */
}

/* card盒子 */
.card {
  position: relative;
  width: 250px;
  height: 300px;
  margin: 20px;
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.2);
  border-radius: 15px;
  display: flex;
  justify-content: center;
  align-items: center;
  backdrop-filter: blur(10px);
}

/* 上面图片部分盒子样式 */
.card .content {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  transition: 0.5s;
  width: 100%;
}

.card:hover .content {
  opacity: 1;
  transform: translateY(-20px);
  width: 100%;
}

.card .content .imgBx {
  position: relative;
  width: 150px;
  height: 150px;
  overflow: hidden;
}

.card .content .imgBx img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 图片下方文字 */
.card .content .contentBx h3 {
  color: #000000;
  text-transform: uppercase;
  letter-spacing: 2px;
  font-weight: 500;
  font-size: 18px;
  text-align: center;
  margin: 20px 0 10px;
  line-height: 1.1em;
}

.card .content .contentBx h3 span {
  font-size: 12px;
  font-weight: 300;
  text-transform: initial;
}

/* 下方三个小图片部分 */
.card .sci {
  position: absolute;
  bottom: -35px;
  display: flex;
  padding: 0;
  color: rgb(96, 98, 102);
}

.card .sci li {
  list-style: none;
  transform: translateY(40px);
  transition: 0.5s;
  opacity: 0;
  transition-delay: calc(0.1s * var(--i));
  margin: 0 3px;
}

.card:hover .sci li {
  transform: translateY(0px);
  opacity: 1;
  cursor: pointer;
}

.card .sci li span:hover {
  color: #0084ff;
}

.card .sci li:nth-child(4) span:hover {
  color: red;
}

.type-label {
  margin-left: 20px;
  font-size: 24px;
}

.btn-head {
  position: sticky;
  top: 0;
  z-index: 10; /* 防止被卡片盖住 */
  background: white; /* 背景色，避免滚动时透出内容 */
  padding: 20px;
}

.loading {
  width: 100%;
  text-align: center;
  padding: 20px;
  color: #888;
}

/* 自定义滚动条（仅现代浏览器支持） */
.right-body::-webkit-scrollbar {
  width: 0px; /* 滚动条宽度 */
}

.right-body::-webkit-scrollbar-track {
  background: #f5f5f5; /* 滚动条轨道颜色 */
  border-radius: 3px;
}

.right-body::-webkit-scrollbar-thumb {
  background: #ccc; /* 滚动条滑块颜色 */
  border-radius: 3px;
}

.right-body::-webkit-scrollbar-thumb:hover {
  background: #999; /* 滑块hover颜色 */
}
</style>
